package br.com.treinamento.gestaoExperienciaProfissional.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.treinamento.gestaoExperienciaProfissional.model.Usuario;

@WebFilter(urlPatterns = "/paginas/*")
public class LoginFilter implements Filter {

	private static final String URL_LOGIN = "login.jsf";
	private static final String URL_PAGINA_INICIAL = "/paginas/paginaInicial.jsf";

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		Usuario usuario = obterUsuarioLogado(httpServletRequest);
		if (usuario == null) {
			redirecionaPaginaLogin(response, httpServletRequest);
		} else {
			String paginaSolicitada = httpServletRequest.getServletPath();
			if (!paginaSolicitada.equals(URL_PAGINA_INICIAL) && !usuario.verificaAcessoUrl(paginaSolicitada)) {
				((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
			}
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
	}

	private void redirecionaPaginaLogin(ServletResponse response, HttpServletRequest httpServletRequest) throws IOException {
		String urlLogin = getLoginUrl(httpServletRequest);
		((HttpServletResponse) response).sendRedirect(urlLogin);
	}

	private static Usuario obterUsuarioLogado(HttpServletRequest request) {
		return (Usuario) request.getSession().getAttribute("usuario");
	}

	private String getLoginUrl(HttpServletRequest httpServletRequest) {
		return String.format("%s/%s", httpServletRequest.getContextPath(), URL_LOGIN);
	}

}
